package com.avic.process.panels;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.border.TitledBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import com.avic.process.utils.Model;
import com.avic.process.utils.MyTreeUtil;
import com.avic.process.utils.SpecialSymbolUtil;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCSession;

public class TreePanel extends JScrollPane {
	private TCSession tcsession;
	private String name, preferenceName;
	
	private static final long serialVersionUID = 1L;

	public TreePanel(TCSession tcsession, String name, String preferenceName) {
		this.tcsession = tcsession;
		this.name = name;
		this.preferenceName = preferenceName;
		initUI();
	}
	
	private void initUI() {
		setBorder(new TitledBorder(name));
		TCPreferenceService pre = tcsession.getPreferenceService();
		String[] dbConfig = pre.getStringArray(TCPreferenceService.TC_preference_site, preferenceName);
		final JTree jtree = new MyTreeUtil().getTree(dbConfig);
		jtree.expandPath(jtree.getPathForRow(0));
		jtree.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (!MainPanel.isEdit) {
					return;
				}
				if (e.getButton() != MouseEvent.BUTTON1 || e.getClickCount() != 2) {
					return;
				}
				TreePath path = jtree.getPathForLocation(e.getX(), e.getY());
				if (null == path) {
					return;
				}
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
						.getLastPathComponent();
				if (!node.isLeaf()) {
					return;
				}
				Model model = (Model) node.getUserObject();
				if (null == model) {
					return;
				}
				SpecialSymbolUtil.insert(null == model.value ? model.name : model.value);
			}
		});
		setViewportView(jtree);
	}
}
